$(document).ready(function() {
//	$("#t_devis img[title]").tooltip();
	 $("#changeEcheance_dial").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		height: "280",
		width: "300",
		buttons: {
			 "Fermer": function(){
				  $(this).dialog("close");
			 },
			 "Valider": function(){
					 doChangerEcheance();
			 }
		}
		
	});
	 $("#changeDate_dial").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		height: "280",
		width: "300",
		buttons: {
			 "Fermer": function(){
				  $(this).dialog("close");
			 },
			 "Valider": function(){
					 doChangerDate();
			 }
		}
		
	});

	$("#crer_devis_tabs").tabs();
	$('textarea.tinymce').tinymce({
		script_url : '/public/javascript/tinymce/jscripts/tiny_mce/tiny_mce.js',
		theme : "simple"
	});
	$('#t_devis').fixheadertable({
		colratio: [40,,120,120,150],
		zebra : true,
		zebraClass : 'ui-state-active',
		sortable: true,
		sortType : ['integer','string','date','integer','string'],
		pager: true,
		rowsPerPage: 25,
		
	});
	$('#t_facture').fixheadertable({
		colratio: [50,,120,120,120,100],
		zebra : true,
		sortable: true,
		sortType : ['integer','string','date','date','integer','string'],
		pager: true,
		rowsPerPage: 25
	});
	$('#t_paiements').fixheadertable({
		colratio: [50,,120,120,40],
		zebra : true,
		sortable: true,
		sortType : ['integer','string','date','integer','string'],
		pager: true,
		rowsPerPage: 25
	});
	$("#nouveau_devis").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: '1000',
		height: '720',
		buttons: {
			"Annuler": function (){
				$(this).dialog('close');
			},
			"Valider": function (){
				newDevis();
			}
		}
	});
	$("#newDevisOK_dial").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		buttons: {
			"OK": function (){
				window.location = "/ventes?devis";
			}
		}
	});
	$("#devis_lines").fixheadertable({
		sortable: false,
		pager: false,
		rowsPerPage: 10,
		colratio: [300,100,100,100,100,''],
	});
	$("#carnetAddress").fixheadertable({
		colratio: [50,200,''],
		zebra : true,
		sortable: true,
		sortType : ['string','string','string'],
		pager: true,
		rowsPerPage: 25
	});
	$(".datepicker").datepicker({
		dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
		monthNames: ['Janvier','F"vrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Decembre'],
		dayNamesMin: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
		dateFormat: 'dd-mm-yy'
	});
	$("#preview").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: '700px',
		buttons: {
			"Fermer": function (){
				$(this).dialog('close');
			}
		}
	});
});
function calc_line(i){
	if(i){
		var qte = $("#qte_"+i).val();
		var montant = $("#ht_"+i).val();
		var tva = $("#tva_"+i+" :selected").text();
		tva = parseFloat(tva.replace("%",""));
		
		$("#montant_ht_"+i).val((qte*montant)+" €");
	}
	
	var tot_ht = 0;
	var tot_55 = 0;
	var tot_196 = 0;
	var tot_ttc = 0;
	var a_payer = 0;
	for(var n=1 ; n<=20 ; n++){
		q = parseFloat($("#qte_"+n).val());
		m = parseFloat($("#ht_"+n).val());
		if(!isNaN(q) && !isNaN(m)){
			tot_ht += (q * m);
			t = $("#tva_"+n+" :selected").text();
			t = parseFloat(t.replace("%",""));
			if(t == 5.5){
				tot_55 += ((q * m) * 0.055);
			}else if(t == 19.6){
				tot_196 += ((q * m) * 0.196);
			}
		}
	}
	tot_ttc = tot_ht + tot_55 + tot_196;
	$("#tot_ht").html(tot_ht+" &euro;");
	$("#montant_55").html(tot_55+" &euro;");
	$("#montant_196").html(tot_196+" &euro;");
	var remise = parseFloat($("#remise").val());
	if(!isNaN(remise)){
		remise = parseFloat((tot_ttc*remise)/100);
		a_payer = (tot_ttc - remise);
		$("#montant_remise").html(remise+" &euro;");
	}else{
		a_payer = tot_ttc;
	}
	var accompte = parseFloat($("#accompte").val());
	if(!isNaN(accompte)){
		$("#montant_accompte").html(accompte+" &euro;");
		a_payer -= accompte;
	}else{
		accompte = 0;
	}
	$("#tot_ttc").html(tot_ttc+" &euro;");
	$("#a_payer").html(a_payer + " &euro;");
	// input hidden
	$("input[name=montant_ht]").val(tot_ht);
	$("input[name=montant_ttc]").val(tot_ttc);
	$("input[name=montant_55]").val(tot_55);
	$("input[name=montant_196]").val(tot_196);
	$("input[name=montant_remise]").val(remise);
	$("input[name=accompte]").val(accompte);
}
function newDevis(){
	var postVars = $("#new_devis").serializeArray();
	
	var contact_id = $("input[name=contact_id]").val();
	var date = $("input[name=date]").val();
	var echeance = $("input[name=echeance]").val();
	var tot_ttc = $("input[name=montant_ttc]").val(); 
	
	
	if(contact_id == "" || date == "" || echeance == "" || tot_ttc == "" || parseInt(tot_ttc) == 0){
		alert("Veuillez remplir tous les champs");
	}else{
	
		$.ajax({
	        type: "POST",
	        url: '/ventes/xhr/newDevis',
	        dataType: "json",
	        data: postVars,
	        success: function(data){
	        	if(data.response_code == "ok"){
	        		if($("#devis_id").val() != ""){
	        			$("#newDevisOK_dial").html("Devis mis à jour");
	        		}else{
	        			$("#newDevisOK_dial").html("Nouveau devis enregistré");
	        		}
	        		$("#newDevisOK_dial").dialog('open');
	        	}else{
	        		alert("Une erreur est survenue");
	        	}
	        }
		});
	}
}
function editDevis(id){
	$.ajax({
        type: "POST",
        url: '/ventes/devis/get/'+id,
        dataType: "json",
        success: function(data){
        	$("input[name=date]").val(data.date);
        	$("input[name=echeance]").val(data.echeance);
        	$("input[name=remise]").val(data.remise);
        	var name = "#option_type_reglement_"+data.type_reglement;
        	$(name).attr("selected",true);
        	$("input[name=accompte]").val(data.accompte);
        	$("input[name=ref_commande]").val(data.ref_commande);
        	$("#contact_"+data.contact_id).attr("checked",true);
        	var n = 1;
        	for(var i in data.lines){
        		$("#desc_"+n).text(data.lines[i].description);
        		$("#qte_"+n).val(data.lines[i].qte);
        		$("#ht_"+n).val(data.lines[i].montant_ht);
        		name = "#option_plan_"+n+"_"+data.lines[i].classe;
            	$(name).attr("selected",true);
            	name = "#option_tva_"+n+"_"+data.lines[i].taux_tva;
            	$(name).attr("selected",true);
        		calc_line(n);
        		n++;
        	}
        	calc_line();
        	$("#devis_id").val(data._id);
        	$('#nouveau_devis').dialog('open');
        }
	});
}
function removeDevis(id){
	if(confirm("Supprimer le devis?")){
		$.ajax({
	        type: "POST",
	        url: '/ventes/devis/remove/'+id,
	        dataType: "json",
	        success: function(data){
	        	window.location = "/ventes?devis";
	        }
		});
	}
}
function facturerDevis(id){
	if(confirm("Transformer le devis en facture?")){
		$.ajax({
	        type: "POST",
	        url: '/ventes/devis/facturer/'+id,
	        dataType: "json",
	        success: function(data){
	        	window.location = "/ventes?factures";
	        }
		});
	}
}
function removeFacture(id){
	if(confirm("Supprimer la facture?")){
		$.ajax({
	        type: "POST",
	        url: '/ventes/facture/remove/'+id,
	        dataType: "json",
	        success: function(data){
	        	window.location = "/ventes?factures";
	        }
		});
	}
}
function removePaiement(facture_id){
	if(confirm("Supprimer le paiement?")){
		$.ajax({
	        type: "POST",
	        url: '/ventes/paiement/remove/'+facture_id,
	        dataType: "json",
	        success: function(data){
	        	window.location = "/ventes?paiements";
	        }
		});
	}
}
function enregistrerPaiement(facture_id){
	if(confirm("Enregister le paiement de la facture?")){
		$.ajax({
	        type: "POST",
	        url: '/ventes/paiement/enregistrer/'+facture_id,
	        dataType: "json",
	        success: function(data){
	        	window.location = "/ventes?paiements";
	        }
		});
	}
}
function previewDevis(id){
	$.ajax({
        type: "POST",
        url: '/preview/devis/'+id,
        dataType: "html",
        success: function(data){
        	$("#preview").html(data);
        	$("#preview").dialog('open');
        }
	});
}
function previewFacture(id){
	$.ajax({
        type: "POST",
        url: '/preview/facture/'+id,
        dataType: "html",
        success: function(data){
        	$("#preview").html(data);
        	$("#preview").dialog('open');
        }
	});
}
function changeEcheance(id){
	 $("#changeEcheance_dial").dialog("open");
	 $("#echeance_factureid").val(id);
}
function doChangerEcheance(){
  var new_echeance = $("#new_echeance").val();
  $("input[name=echeance]").val(new_echeance);
  var postVars = $("#changerEcheance_form").serializeArray();
  $.ajax({
        type: "POST",
        url: '/ventes/facture/updateEcheance',
		  dataType: "json",
	     data: postVars,
	     success: function(data){
				window.location = "/ventes?factures";
        }
	});
}
function changeDate(id){
	 $("#changeDate_dial").dialog("open");
	 $("#date_factureid").val(id);
}
function doChangerDate(){
  var new_date = $("#new_date").val();
  $("input[name=date]").val(new_date);
  var postVars = $("#changerDate_form").serializeArray();
  $.ajax({
        type: "POST",
        url: '/ventes/facture/updateDate',
		  dataType: "json",
	     data: postVars,
	     success: function(data){
				window.location = "/ventes?factures";
        }
	});
}